package dca.sistemascontrole.view.configuracao;

import dca.sistemascontrole.handler.HandlerMainFrame;
import dca.sistemascontrole.handler.HandlerPainelMalhaVisível;
import dca.sistemascontrole.malhadecontrole.MalhaAberta;
import dca.sistemascontrole.sinais.Sinal;
import java.awt.event.HierarchyEvent;
import java.awt.event.HierarchyListener;
import javax.swing.JOptionPane;

/**
 *
 * @author Rafael
 */
public class PanelMalhaAberta extends javax.swing.JPanel {

    private int tipoDeSinal;
    private HandlerMainFrame handlerMainFrame;

    public PanelMalhaAberta(HandlerMainFrame handlerMainFrame) {
        initComponents();

        this.handlerMainFrame = handlerMainFrame;

        addHierarchyListener(new HierarchyListener() {
            public void hierarchyChanged(HierarchyEvent e) {
                hierarchyChangedEvent();
            }
        });

    }

    private void hierarchyChangedEvent() {
        boolean isExibidoAtual = isShowing();
        if (HandlerPainelMalhaVisível.getMalhaAtual() != HandlerPainelMalhaVisível.MALHA_ABERTA && isExibidoAtual) {
            buttonGroupSinais.clearSelection();
            handlerMainFrame.interromper();
            btnSend.setEnabled(false);
            
            HandlerPainelMalhaVisível.setMalhaAtual(HandlerPainelMalhaVisível.MALHA_ABERTA);
        }
    }

    private void setTipoSinal(int tipo) {
        tipoDeSinal = tipo;
        btnSend.setEnabled(true);

        if (tipo == Sinal.DEGRAU) {
            txtPeriodo.setEnabled(false);
            txtFrequencia.setEnabled(false);
            txtOffset.setEnabled(false);
        } else {
            txtPeriodo.setEnabled(true);
            txtFrequencia.setEnabled(true);
            txtOffset.setEnabled(true);
        }
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        buttonGroupSinais = new javax.swing.ButtonGroup();
        jPanel10 = new javax.swing.JPanel();
        radioDegrau = new javax.swing.JRadioButton();
        radioSenoidal = new javax.swing.JRadioButton();
        radioQuadrada = new javax.swing.JRadioButton();
        radioDenteSerra = new javax.swing.JRadioButton();
        radioAleatorio = new javax.swing.JRadioButton();
        jPanel11 = new javax.swing.JPanel();
        jLabel9 = new javax.swing.JLabel();
        jLabel10 = new javax.swing.JLabel();
        txtAmplitude = new javax.swing.JTextField();
        jLabel11 = new javax.swing.JLabel();
        txtPeriodo = new javax.swing.JTextField();
        jLabel12 = new javax.swing.JLabel();
        jLabel13 = new javax.swing.JLabel();
        txtFrequencia = new javax.swing.JTextField();
        jLabel14 = new javax.swing.JLabel();
        btnSend = new dca.sistemascontrole.view.components.CustomButton();
        jLabel15 = new javax.swing.JLabel();
        txtOffset = new javax.swing.JTextField();
        jLabel16 = new javax.swing.JLabel();

        setBackground(new java.awt.Color(255, 255, 255));

        jPanel10.setBackground(new java.awt.Color(255, 255, 255));
        jPanel10.setBorder(javax.swing.BorderFactory.createTitledBorder("Sinais de Controle"));

        radioDegrau.setBackground(new java.awt.Color(255, 255, 255));
        buttonGroupSinais.add(radioDegrau);
        radioDegrau.setSelected(true);
        radioDegrau.setText("Degrau");
        radioDegrau.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                radioDegrauActionPerformed(evt);
            }
        });

        radioSenoidal.setBackground(new java.awt.Color(255, 255, 255));
        buttonGroupSinais.add(radioSenoidal);
        radioSenoidal.setText("Senoidal");
        radioSenoidal.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                radioSenoidalActionPerformed(evt);
            }
        });

        radioQuadrada.setBackground(new java.awt.Color(255, 255, 255));
        buttonGroupSinais.add(radioQuadrada);
        radioQuadrada.setText("Quadrada");
        radioQuadrada.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                radioQuadradaActionPerformed(evt);
            }
        });

        radioDenteSerra.setBackground(new java.awt.Color(255, 255, 255));
        buttonGroupSinais.add(radioDenteSerra);
        radioDenteSerra.setText("Dente de Serra");
        radioDenteSerra.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                radioDenteSerraActionPerformed(evt);
            }
        });

        radioAleatorio.setBackground(new java.awt.Color(255, 255, 255));
        buttonGroupSinais.add(radioAleatorio);
        radioAleatorio.setText("Aleatório");
        radioAleatorio.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                radioAleatorioActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel10Layout = new javax.swing.GroupLayout(jPanel10);
        jPanel10.setLayout(jPanel10Layout);
        jPanel10Layout.setHorizontalGroup(
            jPanel10Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel10Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel10Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(radioDenteSerra, javax.swing.GroupLayout.DEFAULT_SIZE, 142, Short.MAX_VALUE)
                    .addComponent(radioDegrau, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel10Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel10Layout.createSequentialGroup()
                        .addComponent(radioSenoidal, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(radioQuadrada, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGroup(jPanel10Layout.createSequentialGroup()
                        .addComponent(radioAleatorio, javax.swing.GroupLayout.DEFAULT_SIZE, 111, Short.MAX_VALUE)
                        .addGap(101, 101, 101)))
                .addContainerGap())
        );
        jPanel10Layout.setVerticalGroup(
            jPanel10Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel10Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel10Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(radioDegrau)
                    .addComponent(radioSenoidal)
                    .addComponent(radioQuadrada))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel10Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(radioDenteSerra)
                    .addComponent(radioAleatorio))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jPanel11.setBackground(new java.awt.Color(255, 255, 255));
        jPanel11.setBorder(javax.swing.BorderFactory.createTitledBorder("Configurar Sinal"));

        jLabel9.setText("Amplitude:");

        jLabel10.setText("Período:");

        jLabel11.setText("(V)");

        txtPeriodo.addCaretListener(new javax.swing.event.CaretListener() {
            public void caretUpdate(javax.swing.event.CaretEvent evt) {
                txtPeriodoCaretUpdate(evt);
            }
        });

        jLabel12.setText("(s)");

        jLabel13.setText("Frequencia:");

        txtFrequencia.addCaretListener(new javax.swing.event.CaretListener() {
            public void caretUpdate(javax.swing.event.CaretEvent evt) {
                txtFrequenciaCaretUpdate(evt);
            }
        });

        jLabel14.setText("(Hz)");

        btnSend.setBackground(new java.awt.Color(250, 250, 250));
        btnSend.setText("Enviar");
        btnSend.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSendActionPerformed(evt);
            }
        });

        jLabel15.setText("Offset:");

        jLabel16.setText("(V)");

        javax.swing.GroupLayout jPanel11Layout = new javax.swing.GroupLayout(jPanel11);
        jPanel11.setLayout(jPanel11Layout);
        jPanel11Layout.setHorizontalGroup(
            jPanel11Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel11Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel11Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel11Layout.createSequentialGroup()
                        .addComponent(jLabel15)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtOffset, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel16)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 119, Short.MAX_VALUE)
                        .addComponent(btnSend, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel11Layout.createSequentialGroup()
                        .addGroup(jPanel11Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel11Layout.createSequentialGroup()
                                .addComponent(jLabel13)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(txtFrequencia, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jLabel14))
                            .addGroup(jPanel11Layout.createSequentialGroup()
                                .addComponent(jLabel10)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(txtPeriodo, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jLabel12))
                            .addGroup(jPanel11Layout.createSequentialGroup()
                                .addComponent(jLabel9)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(txtAmplitude, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jLabel11)))
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );

        jPanel11Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jLabel10, jLabel13, jLabel15, jLabel9});

        jPanel11Layout.setVerticalGroup(
            jPanel11Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel11Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel11Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel9)
                    .addComponent(txtAmplitude, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel11))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel11Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel10)
                    .addComponent(txtPeriodo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel12))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel11Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel13)
                    .addComponent(txtFrequencia, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel14))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel11Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel15)
                    .addComponent(txtOffset, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel16)
                    .addComponent(btnSend, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel10, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel11, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel10, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel11, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(25, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void radioDegrauActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_radioDegrauActionPerformed
        setTipoSinal(Sinal.DEGRAU);
    }//GEN-LAST:event_radioDegrauActionPerformed

    private void radioSenoidalActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_radioSenoidalActionPerformed
        setTipoSinal(Sinal.SENOIDAL);
    }//GEN-LAST:event_radioSenoidalActionPerformed

    private void radioQuadradaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_radioQuadradaActionPerformed
        setTipoSinal(Sinal.QUADRADA);
    }//GEN-LAST:event_radioQuadradaActionPerformed

    private void radioDenteSerraActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_radioDenteSerraActionPerformed
        setTipoSinal(Sinal.DENTE_DE_SERRA);
    }//GEN-LAST:event_radioDenteSerraActionPerformed

    private void radioAleatorioActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_radioAleatorioActionPerformed
        setTipoSinal(Sinal.ALEATORIO);
    }//GEN-LAST:event_radioAleatorioActionPerformed

    private void txtPeriodoCaretUpdate(javax.swing.event.CaretEvent evt) {//GEN-FIRST:event_txtPeriodoCaretUpdate
        try {
            if (txtPeriodo.hasFocus()) {
                float periodo = Float.parseFloat(txtPeriodo.getText());

                txtFrequencia.setText(String.valueOf(1 / periodo));
            }
        } catch (NumberFormatException ex) {
        } catch (IllegalStateException ex) {
        }
    }//GEN-LAST:event_txtPeriodoCaretUpdate

    private void txtFrequenciaCaretUpdate(javax.swing.event.CaretEvent evt) {//GEN-FIRST:event_txtFrequenciaCaretUpdate
        try {
            if (txtFrequencia.hasFocus()) {
                float frequencia = Float.parseFloat(txtFrequencia.getText());

                txtPeriodo.setText(String.valueOf(1 / frequencia));
            }
        } catch (NumberFormatException ex) {
        } catch (IllegalStateException ex) {
        }
    }//GEN-LAST:event_txtFrequenciaCaretUpdate

    private void btnSendActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSendActionPerformed
        String amplitude = txtAmplitude.getText().trim().replace(",", ".");
        if (!validarEntrada(amplitude)) {
            JOptionPane.showMessageDialog(this, "Amplitude invalida.");
            return;
        }

        String offset = "0";
        String periodo = "0";
        String frequencia = "0";
        if (tipoDeSinal != Sinal.DEGRAU) {
            offset = txtOffset.getText().trim().replace(",", ".");
            if (!validarEntrada(offset)) {
                JOptionPane.showMessageDialog(this, "Offset invalida.");
                return;
            }

            periodo = txtPeriodo.getText().trim().replace(",", ".");
            if (!validarEntrada(periodo)) {
                JOptionPane.showMessageDialog(this, "Período invalido.");
                return;
            }

            frequencia = txtFrequencia.getText().trim().replace(",", ".");
            if (!validarEntrada(frequencia)) {
                JOptionPane.showMessageDialog(this, "Frquencia invalida.");
                return;
            }
        }

        Sinal sinal = Sinal.gerarSinal(tipoDeSinal, Float.parseFloat(periodo) * 1000, Float.parseFloat(amplitude), Float.parseFloat(frequencia), Float.parseFloat(offset));
        handlerMainFrame.setMalhaDeControle(new MalhaAberta(sinal));
    }//GEN-LAST:event_btnSendActionPerformed

    private boolean validarEntrada(String s) {
        try {
            Float.parseFloat(s);
        } catch (NumberFormatException ex) {
            return false;
        }

        return true;
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private dca.sistemascontrole.view.components.CustomButton btnSend;
    private javax.swing.ButtonGroup buttonGroupSinais;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel12;
    private javax.swing.JLabel jLabel13;
    private javax.swing.JLabel jLabel14;
    private javax.swing.JLabel jLabel15;
    private javax.swing.JLabel jLabel16;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JPanel jPanel10;
    private javax.swing.JPanel jPanel11;
    private javax.swing.JRadioButton radioAleatorio;
    private javax.swing.JRadioButton radioDegrau;
    private javax.swing.JRadioButton radioDenteSerra;
    private javax.swing.JRadioButton radioQuadrada;
    private javax.swing.JRadioButton radioSenoidal;
    private javax.swing.JTextField txtAmplitude;
    private javax.swing.JTextField txtFrequencia;
    private javax.swing.JTextField txtOffset;
    private javax.swing.JTextField txtPeriodo;
    // End of variables declaration//GEN-END:variables
}
